package com.homedo.odin.solution.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dangdang.ddframe.rdb.sharding.id.generator.IdGenerator;
import com.dangdang.ddframe.rdb.sharding.id.generator.self.IPIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.base.service.BaseService;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.DateUtils;
import com.homedo.core.common.util.NumberHelper;
import com.homedo.odin.solution.dao.DailyCountMapper;
import com.homedo.odin.solution.dao.SolutionMapper;
import com.homedo.odin.solution.dao.UserSolutionMapper;
import com.homedo.odin.solution.enumcode.BrandStatusEnum;
import com.homedo.odin.solution.enumcode.basic.DeleteEnum;
import com.homedo.odin.solution.enumcode.basic.ViewDownloadEnum;
import com.homedo.odin.solution.model.dto.BrandFirmSolutionResponseBean;
import com.homedo.odin.solution.model.dto.PageBean;
import com.homedo.odin.solution.model.dto.SolutionListResponseBean;
import com.homedo.odin.solution.model.dto.UserSolutionCount;
import com.homedo.odin.solution.model.entity.BrandFirm;
import com.homedo.odin.solution.model.entity.BrandOwner;
import com.homedo.odin.solution.model.entity.DailyCount;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.request.pc.brand.PcBrandSolutionListRequestBean;
import com.homedo.odin.solution.model.response.pc.brand.BrandFirmSolutionPageResponseBean;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p> 方案 服务实现类 </p>
 *
 * @author HarveyDing
 * @since 2018-03-08
 */
@Service
public class SolutionServiceImpl extends BaseService<SolutionMapper, Solution> {

    @Autowired
    private DailyCountMapper dailyCountMapper;
    @Autowired
    private SolutionMapper solutionMapper;
    @Autowired
    private UserSolutionMapper userSolutionMapper;
    @Autowired
    private SolutionSkuServiceImpl solutionSkuService;
    @Autowired
    private BrandFirmServiceImpl brandFirmService;
    @Autowired
    private BrandOwnerServiceImpl brandOwnerService;


    public Solution getSolution(Long solutionId) {
        return solutionMapper.getSolution(solutionId);
    }

    public List<Solution> selectSolsByUserIdAndStatus(Integer userId, Integer status) {
        Map<String, Object> map = new HashMap<>();
        map.put("is_del", 0);
        if (status != null) {
            map.put("status", status);
        }
        map.put("user_id", userId);
        return baseMapper.selectByMap(map);
    }

    public Solution findBySolutionId(Long solutionId) {
        Solution solution = new Solution();
        solution.setSolutionId(solutionId);
        solution.setIsDel(DeleteEnum.NOT_DEL.getDbValue());
        return baseMapper.selectOne(solution);
    }

    public List<Solution> findBySolutionIds(List<Long> solutionIds) {
        return baseMapper.findBySolutionIds(solutionIds);
    }


    public List<SolutionListResponseBean> querySolutionsByParams(Integer solutionType, Integer brandId, Integer sysAttr,
            Integer buildingType, Integer status, Integer userId) {
        return baseMapper.querySolutionsByParams(solutionType, brandId, sysAttr, buildingType, status, userId);
    }

    public void addSolutionPageView(Long solutionId) {
        //增加每日统计的记录
        //获取当前时间
        Date nowDate = DateUtils.parseDate(new Date());
        DailyCount dailyCount = dailyCountMapper
                .queryDailyCountToDay(solutionId, ViewDownloadEnum.VIEWS.getDbValue(), nowDate);
        if (dailyCount == null) {
            //为空则新建
            Solution solution = solutionMapper.selectById(solutionId);
            DailyCount addDailyCount = new DailyCount();
            addDailyCount.setObjectId(solutionId);
            addDailyCount.setObjectName(solution.getSolutionName());
            addDailyCount.setObjectType(1);
            addDailyCount.setDataType(ViewDownloadEnum.VIEWS.getDbValue());
            addDailyCount.setAmount(1);
            addDailyCount.setCountDate(nowDate);
            dailyCountMapper.insert(addDailyCount);
        } else {
            //增加数量
            dailyCountMapper.addDailyCount(solutionId, ViewDownloadEnum.VIEWS.getDbValue(), nowDate);
        }
        solutionMapper.addSolutionPageView(solutionId);
    }

    /**
     * 获取热榜信息
     *
     * @param type 类型 1：昨日热榜 2：周热榜 3：月热榜
     * @param number 获取数量
     */
    public List<SolutionListResponseBean> queryHotSolutionList(Integer type, Integer number) {
        Date startDate = null;
        Date endDate = null;
        //类型 1：昨日热榜 2：周热榜 3：月热榜
        if (type.intValue() == 1) {
            //获取前一天的日期
            Date lastDate = DateUtils.getLastDate();
            startDate = lastDate;
            endDate = lastDate;
        } else if (type.intValue() == 2) {
            Map<String, Date> lastWeek = DateUtils.getLastWeek();
            startDate = lastWeek.get("monday");
            endDate = lastWeek.get("sunday");
        } else if (type.intValue() == 3) {
            String beforeFirstMonthdate = DateUtils.getBeforeFirstMonthdate();
            startDate = DateUtils.parseDate(beforeFirstMonthdate);
            String beforeLastMonthdate = DateUtils.getBeforeLastMonthdate();
            endDate = DateUtils.parseDate(beforeLastMonthdate);
        }
        return solutionMapper.queryHotSolutionList(startDate, endDate, number);
    }

    public List<Solution> querySolutionListForHome(Integer number) {
        return solutionMapper.querySolutionListForHome(number);
    }

    public List<Solution> querySolutionForPri(Long solutionId, String solutionName, Integer solutionType,
            Integer isAdmitDownload, String expertName, Integer brandId, Integer status, String businessCode,
            String sortString, Integer isDel, String userName, Integer formType) {

        return solutionMapper
                .querySolutionForPri(solutionId, solutionName, solutionType, isAdmitDownload, expertName, brandId,
                        status, businessCode, sortString, isDel, userName, formType);
    }

    public Solution getSolutionByBusinessCode(String businessCode) {
        Solution solution = new Solution();
        solution.setBusinessCode(businessCode);
        solution.setIsDel(0);
        return solutionMapper.selectOne(solution);
    }

    public Long addSolution(Solution solution) {
        IdGenerator ipIdGenerator = new IPIdGenerator();
        Long solutionId = (Long) ipIdGenerator.generateId();
        solution.setSolutionId(solutionId);
        solutionMapper.insert(solution);
        return solutionId;
    }

    public void updateDel(Long solutionId, Integer status) {
        solutionMapper.updateDel(solutionId, status);
    }

    public Integer updateSort(Long solutionId, Integer sort) {
        return solutionMapper.updateSort(solutionId, sort);
    }

    public void editSolution(Solution solution) {
        solutionMapper.updateById(solution);
    }

    /**
     * 获取品牌商方案统计
     */
    public UserSolutionCount queryUserSolutionCount(Integer userId, Integer status, Integer solutionType) {
        return baseMapper.queryUserSolutionCount(userId, status, solutionType);
    }

    public Solution findByUserId(Integer userId) {
        Solution solution = new Solution();
        solution.setUserId(userId);
        solution.setIsDel(0);
        return baseMapper.selectOne(solution);
    }

    public List<Solution> findSolutionByUserId(Integer userId) {
        Wrapper<Solution> wrapper = new EntityWrapper<Solution>();
        wrapper.eq("user_id", userId);
        wrapper.eq("is_del", 0);
        return baseMapper.selectList(wrapper);
    }

    public void handleStateChange(Long solutionId, Integer fromStatus, Integer toStatus, String operator,
            String auditOpinion) {
        solutionMapper.handleStateChange(solutionId, fromStatus, toStatus, operator, auditOpinion);
    }

    public List<Solution> findListBySkuId(String skuId) {
        return solutionMapper.findListBySkuId(skuId);
    }

    public List<Solution> queryMySolutionForPc(Integer solutionType, Integer sysAttr, Integer buildingType,
            Integer shelveTimeSort,
            Integer createTimeSort, Integer downloadCountSort, Integer viewCountSort,
            Integer commentCountSort, Integer status, Integer expType, Integer uid,
            Integer brandId) {
        return solutionMapper.queryMySolutionForPc(solutionType, sysAttr, buildingType, shelveTimeSort,
                createTimeSort, downloadCountSort, viewCountSort, commentCountSort, status, expType, uid, brandId);
    }

    public List<Solution> querySolutionForPc(Integer solutionType, Integer sysAttr, Integer buildingType,
            Integer shelveTimeSort,
            Integer createTimeSort, Integer downloadCountSort, Integer viewCountSort,
            Integer commentCountSort, Integer status, Integer expType, Integer uid, Integer brandId) {
        return solutionMapper.querySolutionForPc(solutionType, sysAttr, buildingType, shelveTimeSort,
                createTimeSort, downloadCountSort, viewCountSort, commentCountSort, status, expType, uid, brandId);
    }

    public List<Solution> queryFreeSolution4Home(Integer isFree) {
        return solutionMapper.queryFreeSolution4Home(isFree);
    }

    public List<Solution> queryBrandFirmSolution2(Integer loginUserId) {
        return solutionMapper.queryBrandFirmSolution2(loginUserId);
    }

    public List<Solution> queryBrandFirmSolution(Integer uid) {
        return solutionMapper.queryBrandFirmSolution(uid);
    }

    public void addSolutionDownload(Long solutionId) {

        //增加每日统计的记录
        //获取当前时间
        Date nowDate = DateUtils.parseDate(new Date());
        DailyCount dailyCount = dailyCountMapper
                .queryDailyCountToDay(solutionId, ViewDownloadEnum.VIEWS.getDbValue(), nowDate);
        if (dailyCount == null) {

            //为空则新建
            Solution solution = findBySolutionId(solutionId);
            DailyCount addDailyCount = new DailyCount();
            addDailyCount.setObjectId(solutionId);
            addDailyCount.setObjectName(solution.getSolutionName());
            addDailyCount.setObjectType(1);
            addDailyCount.setDataType(ViewDownloadEnum.VIEWS.getDbValue());
            addDailyCount.setAmount(1);
            addDailyCount.setCountDate(nowDate);
            dailyCountMapper.insert(addDailyCount);
        } else {
            //增加数量
            dailyCountMapper.addDailyCount(solutionId, ViewDownloadEnum.VIEWS.getDbValue(), nowDate);
        }
        solutionMapper.addSolutionDownload(solutionId);
    }

    public List<Solution> queryUserSolutionList(Integer userId, String solutionName, Integer status,
            Integer isAdmitDownload, Integer isFree, Integer expType) {
        return solutionMapper.queryUserSolutionList(userId, solutionName, status, isAdmitDownload, isFree, expType);
    }

    public void addSolutionComment(Long solutionId) {
        solutionMapper.addSolutionComment(solutionId);
    }

    public void updateSolutionCollect(Long solutionId, Integer count) {
        solutionMapper.updateSolutionCollect(solutionId, count);
    }


    public List<Solution> findBySolutionIdsAndNotDel(List<Long> solutionIds, int isDel) {
        return solutionMapper.findBySolutionIdsAndNotDel(solutionIds, isDel);
    }


    public BrandFirmSolutionPageResponseBean getBrandFirmSolutions(Integer uid,
            PcBrandSolutionListRequestBean requestBean) {
        BrandFirm brandFirm = brandFirmService.getBrandFirmByUserId(uid);
        if (brandFirm == null || brandFirm.getStatus().intValue() != BrandStatusEnum.AUDITSUCCESS.getKey()) {
            throw new BizException(Meta.CODE_451.getCode(), "该品牌厂商不存在!");
        }
        BrandOwner brandOwner = brandOwnerService.getBrandOwnerById(brandFirm.getBrandId());
        if (brandOwner == null) {
            throw new BizException(Meta.CODE_451.getCode(), "关联品牌主不存在!");
        }

        PageHelper.startPage(requestBean.getPageNum(), requestBean.getPageSize());
        PageInfo<Solution> pageInfo;
        if (NumberHelper.validatePositive(requestBean.getLoginUserId()) && uid.equals(requestBean.getLoginUserId())) {
            pageInfo = new PageInfo<>(queryBrandFirmSolution2(requestBean.getLoginUserId()));
        } else {
            pageInfo = new PageInfo<>(queryBrandFirmSolution(uid));
        }

        List<Solution> queryList = pageInfo.getList();
        List<BrandFirmSolutionResponseBean> responseList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(queryList)) {
            queryList.forEach(solution -> {
                BrandFirmSolutionResponseBean solutionResponse = new BrandFirmSolutionResponseBean();
                BeanUtils.copyProperties(solution, solutionResponse);
                solutionResponse.setFirmName(brandFirm.getFirmName());
                solutionResponse.setBrandIcon(brandOwner.getBrandIcon());
                responseList.add(solutionResponse);
            });
        }

        return BeanUtils.transfrom(BrandFirmSolutionPageResponseBean.class, pageInfo);
    }




}
